<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-20 09:13:33
 * @LastEditors: william
 * @LastEditTime: 2025-04-11 15:49:30
-->
<template>
  <div class="content-container">
    <div class="cc-left">
      <SelectOrganize
        v-if="userInfo.superAdmin"
        v-model="orgId"
        v-model:list="orgOptions"
        :placeholder="$t('userCenter.selectOrganize')"
        @change="getDeptTreeList"
      />
      <TextInput
        v-model="deptName"
        style="margin-top: 5px"
        clearable
        :placeholder="$t('userCenter.deptName')"
      />
      <el-tree
        ref="refTree"
        style="max-width: 600px"
        :data="orgDeptData"
        :props="defaultProps"
        default-expand-all
        :expand-on-click-node="false"
        highlight-current
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      />
    </div>
    <div class="cc-right">
      <el-row
        type="flex"
        justify="space-between"
        class="header-filter four-border-blueBg"
      >
        <div class="row-left">
          <TextInput
            v-model="listParams.userName"
            class="item"
            clearable
            :placeholder="$t('public.userName')"
            verify-type="alnum"
          />
          <TextInput
            v-model="listParams.nickName"
            class="item"
            clearable
            :placeholder="$t('public.nickName')"
          />
          <DateTimeRange
            v-model="timePeriod"
            class="item"
            time-range="30"
            picker-type="2"
          />
          <el-button type="primary" @click="handleQuery">{{
            $t('public.search')
          }}</el-button>
          <el-button plain @click="handleReset">{{
            $t('public.reset')
          }}</el-button>
        </div>
        <div class="row-right">
          <el-button type="primary" @click="handleCreate"
            >+ {{ $t('public.create') }}</el-button
          >
        </div>
      </el-row>
      <div class="base-table-container">
        <BaseTable
          ref="refContentTable"
          v-loading="loading"
          :data="tableData"
          row-key="userId"
        >
          <TableColumn
            prop="userName"
            :label="$t('public.userName')"
            :column-width="columnWidthObj.userName"
          />
          <TableColumn
            prop="nickName"
            :label="$t('public.nickName')"
            :column-width="columnWidthObj.nickName"
          />
          <TableColumn
            prop="roleList"
            :label="$t('userCenter.role')"
            :column-width="columnWidthObj.roleList"
          >
            <template #default="{ row }">
              <span v-if="row.roleList.length">
                <el-tag
                  v-for="item in row.roleList"
                  :key="item"
                  type="success"
                  style="margin-right: 5px"
                  >{{ item.roleName }}</el-tag
                >
              </span>
              <span v-else>--</span>
            </template>
          </TableColumn>
          <TableColumn
            prop="phone"
            :label="$t('public.phone')"
            :column-width="columnWidthObj.phone"
          />
          <TableColumn
            prop="email"
            :label="$t('public.email')"
            :column-width="columnWidthObj.email"
          />
          <TableColumn
            prop="createTime"
            :label="$t('userCenter.joinTime')"
            :column-width="columnWidthObj.createTime"
          />
          <TableColumn
            prop="userType"
            :label="$t('userCenter.userType')"
            :column-width="columnWidthObj.userType"
          >
            <template #default="{ row }">
              <el-tag v-if="row.userType === 1" type="danger">
                {{ $t('userCenter.superAdmin') }}</el-tag
              >
              <el-tag v-else-if="row.isDeptAdmin" type="success">{{
                $t('userCenter.deptAdmin')
              }}</el-tag>
              <el-tag v-else type="success">{{
                $t('userCenter.regularUser')
              }}</el-tag>
            </template>
          </TableColumn>
          <TableColumn
            prop="action"
            fixed="right"
            :label="$t('public.action')"
            :column-width="columnWidthObj.action"
          >
            <template #default="{ row }">
              <el-button text @click="handleDetailDialog(row)">
                {{ $t('public.detail') }}
              </el-button>
              <el-button
                v-if="row.userType !== 1"
                text
                @click="handleEditDialog(row)"
              >
                {{ $t('public.edit') }}
              </el-button>
              <el-button
                v-if="row.userType !== 1"
                text
                @click="handleDelete(row)"
                >{{ $t('public.delete') }}</el-button
              >
            </template>
          </TableColumn>
        </BaseTable>
        <BasePagination
          v-model:page-size="pageSize"
          v-model:current-page="pageNum"
          :total="total"
          @change="getUserList()"
        />
      </div>
    </div>
    <!-- 新建/编辑 -->
    <AddOrEditDialog
      v-if="addOrEditVisible"
      :id="rowId"
      v-model="addOrEditVisible"
      :type="addOrEditType"
      :dept-id="listParams.deptId"
      @update="handleQuery"
    />
    <!-- 详情 -->
    <DetailDialog
      v-if="detailVisible"
      :id="rowId"
      v-model="detailVisible"
      :dept-id="listParams.deptId"
    />
  </div>
</template>

<script setup>
import AddOrEditDialog from './component/AddOrEditDialog.vue'
import DetailDialog from './component/DetailDialog.vue'

const { userInfo } = storeToRefs(useUserStore())
const orgId = ref('')
const orgOptions = ref([])
const deptName = ref('')
const refTree = ref(null)
const orgDeptData = ref([])
const defaultProps = {
  children: 'childDeptList',
  label: 'label'
}
const listParams = ref({
  deptId: '',
  userName: '',
  nickName: '',
  startTime: '',
  endTime: ''
})
const timePeriod = ref([])
const refContentTable = ref(null)
const loading = ref(false)
const tableData = ref([])
const columnWidthObj = ref({})
const total = ref(0)
const pageSize = ref(10)
const pageNum = ref(1)
const addOrEditVisible = ref(false)
const addOrEditType = ref('detail')
const rowId = ref('')
const detailVisible = ref(false)

watch(
  () => orgOptions.value,
  nv => {
    getDeptTreeList()
    orgId.value = nv[0]?.value || ''
  },
  {
    deep: true
  }
)

watch(deptName, nv => {
  refTree.value.filter(nv)
})

onMounted(() => {
  getDeptTreeList()
})

const handleNodeClick = data => {
  // console.log('handleNodeClick', data)
  listParams.value.deptId = data.deptId
  handleQuery()
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

// 查询部门树节点列表
const getDeptTreeList = () => {
  orgDeptData.value = []
  tableData.value = []
  g_api.userCenter
    .apiDeptTreeList({
      tenantId: orgId.value
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        orgDeptData.value = data
        listParams.value.deptId = data[0]?.deptId || ''
        getUserList()
      }
    })
}

const getUserList = () => {
  loading.value = true
  tableData.value = []
  g_api.userCenter
    .apiUserList({
      ...listParams.value,
      startTime: timePeriod.value[0] || '',
      endTime: timePeriod.value[1] || '',
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        tableData.value = data.items
        total.value = data.total
        useTableColumnWidth({
          refTable: refContentTable.value
        }).getTableColumnWidth(data => {
          columnWidthObj.value = data
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

const handleQuery = () => {
  pageNum.value = 1
  getUserList()
}

const handleReset = () => {
  Object.assign(listParams.value, {
    userName: '',
    nickName: '',
    startTime: '',
    endTime: ''
  })
  timePeriod.value = []
  handleQuery()
}

const handleCreate = () => {
  addOrEditVisible.value = true
  addOrEditType.value = 'add'
}

const handleDetailDialog = row => {
  detailVisible.value = true
  rowId.value = row.userId
}

const handleEditDialog = row => {
  addOrEditVisible.value = true
  addOrEditType.value = 'edit'
  rowId.value = row.userId
}

const handleDelete = row => {
  g_utils
    .deleteConfirm()
    .then(() => {
      loading.value = true
      g_api.userCenter
        .apiUserDelete({
          userId: row.userId
        })
        .then(res => {
          if (res.code === '200') {
            ElMessage.success(res.message)
            handleQuery()
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}
</script>

<style lang="scss" scoped>
.content-container {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  .cc-left {
    max-width: 250px;
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    padding: 10px;
    border-radius: 5px;
    background-color: var(--menu-theme-bg);
    overflow: auto;
    box-sizing: border-box;
    @extend .custom-scrollbar; // 继承滚动条样式
    :deep(.el-tree-node__label) {
      @extend .oneEllipsis;
    }
    :deep(.el-tree) {
      background-color: var(--menu-theme-bg);
    }
  }
  .cc-right {
    display: flex;
    flex-direction: column;
    padding-left: 10px;
    overflow: auto;
  }
}
</style>
